package com.skyworth.web.order.controller;

import com.skyworth.utils.StrUtil;
import com.skyworth.utils.TimeUtil;
import com.skyworth.web.order.domain.OrderModel;
import com.skyworth.web.order.domain.ParentOrderModel;
import com.skyworth.web.order.form.OrderForm;
import com.skyworth.web.order.service.NewOrderService;
import com.skyworth.web.ordermenu.OrderMenuModel;
import com.skyworth.web.ordermenu.OrderMenuService;
import com.skyworth.web.wechat.common.AppSecretInfo;
import com.skyworth.web.wechat.engin.ServerEngin;
import com.skyworth.web.wechat.entity.AccessTokenModel;
import com.skyworth.web.wechat.protocol.NotifyMsg;
import com.skyworth.web.wechat.service.AccessTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yuhaichao on 2016/9/27.
 */
@Controller
@RequestMapping("wechatOrder")
public class WechatOrderController {
    private static final Logger log = LoggerFactory.getLogger(WechatOrderController.class);


    @Autowired
    private NewOrderService newOrderService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private OrderMenuService orderMenuService;

    /**
     * 微信添加一个订单
     * @param orderForm
     * @param model
     * @return
     */
    @RequestMapping(value = {"/api/order/"}, method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> create(HttpServletResponse response, @ModelAttribute OrderForm orderForm, Model model) {
        Map<String,Object> result = new HashMap<>();
        try {
            System.out.println(orderForm);
            System.out.println("tableId:" + orderForm.getTableId() + ",state:" + orderForm.getState());
            if (orderForm == null) {
                result.put("status", "error");
                return result;
            }
            if(orderForm.getState()==NewOrderService.ORDER_CONFIRMED) {
                orderForm.setState(NewOrderService.ORDER_UNCONFIRMED);
            }
            OrderModel orderModel = OrderForm.toOrderModel(orderForm);
            ParentOrderModel parentOrderModel = OrderForm.toParentOrderModel(orderForm);
            orderModel = newOrderService.saveOrUpdate(parentOrderModel, orderModel, orderForm.getFoods());

            if (orderModel != null) {
                if(orderModel.state==NewOrderService.ORDER_CART){
                    result.put("cartOrderId", orderModel.id);
                }
                /*if (orderModel.state == NewOrderService.ORDER_UNCONFIRMED) {
                    final String openid = orderModel.userId;
                    final String orderId = StrUtil.objectToString(orderModel.id);
                    new Thread() {
                        public void run() {

                            AccessTokenModel atm = accessTokenService.findByAppId(AppSecretInfo.appId);
                            String accessToken = atm.getAccessToken();
                            //Map<Object, Object> handleMap = NotifyMsg.orderHandleMsg(openid, orderId);
                            Map<Object,Object> handleMap = NotifyMsg.orderWaitMsg(openid,orderId, TimeUtil.getNowDateFormat("yyyy年MM月dd日 HH:mm"));
                            ServerEngin.getInstance().sendTemplateMsg(accessToken, handleMap);
                        }
                    }.start();
                }*/
                result.put("status", "success");
                result.put("orderId",orderModel.id);
            } else {
                result.put("status", "error");
            }
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return result;
    }

    /**
            * 微信获取当前用户未支付的订单
            * @param userId
    * @return
            */
    @RequestMapping(value = {"/api/getCurrentTableOrder/{userId}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getCurrentTableNoPayOrder(@PathVariable("userId") String userId){
        return newOrderService.getCurrentTableNoPayOrder(userId);
    }

    /**
     * 获取当前台桌未确认的订单列表
     * @param tableId
     * @return
     */
    @RequestMapping(value = {"/api/getCurrentTableNoConfirmOrder/{tableId}"}, method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String,Object>> getCurrentTableNoConfirmOrder(@PathVariable("tableId") Long tableId){
        return null;
        //return newOrderService.getWechatTableConfirmOrder(tableId);
    }

    /**
     * 获取用户支付过的历史订单
     * @param userId
     * @param page
     * @return
     */
    @RequestMapping(value = {"/api/getUserHistoryOrder/{userId}/{page}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getUserHistoryOrder(@PathVariable("userId") String userId,@PathVariable("page") Integer page){
        return newOrderService.getUserHistoryOrder(userId,page,50);
    }

    /**
     * 微信端点击单个历史订单列表中的父订单item，显示父订单合并信息，以及合并的菜单列表(订单列表返回的id是父订单id)
     * @param parentOrderId
     * @return
     */
    @RequestMapping(value = {"/api/getParentOrderById/{parentOrderId}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getParentOrderById(@PathVariable("parentOrderId") long parentOrderId){
        try{
            ParentOrderModel parentOrderModel = newOrderService.getParentOrderById(parentOrderId);
            if(parentOrderModel==null){
                return null;
            }
            Map<String,Object> map = new HashMap<>();
            if(NewOrderService.ORDER_WECHAT_PAYED==parentOrderModel.getState()) {
                Map<String, Object> subOrder = newOrderService.getParentPayOrderDetail(parentOrderId);
                List<OrderMenuModel> menu = null;
                if (subOrder != null) {
                    long parentId = Long.parseLong(StrUtil.objectToString(subOrder.get("orderId")));
                    menu = orderMenuService.findByPayOrderId(parentId);
                }
                map.put("order", subOrder);
                map.put("menu", menu);
            }else if(NewOrderService.ORDER_CONFIRMED==parentOrderModel.getState()){
                Map<String, Object> subOrder = newOrderService.getParentNoPayOrderDetail(parentOrderId);
                List<OrderMenuModel> menu = null;
                if (subOrder != null) {
                    long parentId = Long.parseLong(StrUtil.objectToString(subOrder.get("orderId")));
                    menu = orderMenuService.findByNoPayOrderId(parentId);
                }
                map.put("order", subOrder);
                map.put("menu", menu);
            }
            return map;
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return null;
    }


    /**
     * 微信用户删除订单
     * @param parentOrderId
     * @return
     */
    @RequestMapping(value = {"/api/deleteOrder/{parentOrderId}"}, method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> deleteOrder(@PathVariable("parentOrderId") long parentOrderId){
        Map<String,Object> map = new HashMap<>();
        try{
            newOrderService.deleteOrder(parentOrderId);
            map.put("status","success");
        }catch(Exception e){
            map.put("status","error");
            log.error(e.getMessage());
        }
        return map;
    }

    /**
     * 拉取子订单状态，判断下的订单是否被服务员审核
     * @param subOrderId
     * @return
     */
    @RequestMapping(value = {"/api/qrySubOrderState/{subOrderId}"}, method = RequestMethod.GET)
    @ResponseBody
    public OrderModel qrySubOrderState(@PathVariable("subOrderId") long subOrderId){
        try{
            return newOrderService.qrySubOrderState(subOrderId);
        }catch(Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

}
